package cc.iteachyou.template;

import cc.iteachyou.template.configuration.TemplateEngineConfiguration;
import cc.iteachyou.template.dom.VirtualDOMTree;
import cc.iteachyou.template.tools.StringUtil;
import cc.iteachyou.template.utils.CacheHelper;
import cc.iteachyou.template.utils.RendererHelper;
import cc.iteachyou.template.utils.TemplateHelper;
import cc.iteachyou.template.utils.VariableHelper;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.nodes.Document;

import java.util.Map;

@Slf4j
public class TemplateEngine {
    private TemplateEngineConfiguration configuration;
    private static TemplateEngine engine = null;

    /**
     * 构造函数
     */
    private TemplateEngine(){}

    /**
     * 构造函数
     * @param configuration 模板引擎配置
     */
    private TemplateEngine(TemplateEngineConfiguration configuration){
        this.configuration = configuration;
    }

    /**
     * 获取模板引擎实例
     * @param configuration
     * @return
     */
    public static TemplateEngine getInstance(TemplateEngineConfiguration configuration){
        if(engine == null){
            engine = new TemplateEngine(configuration);
        }
        return engine;
    }

    /**
     * 初始化模板引擎
     */
    public void init() {
        log.info("Dreamer Template Initializing");
        configuration.init();
    }

    public String render(String templateName, Map<String, Object> data){
        // 获取模板引擎助手实例
        TemplateHelper templateHelper = TemplateHelper.getInstance(configuration);
        CacheHelper cacheHelper = CacheHelper.getInstance();

        String content = null;
        // 如果需要缓存模板内容，则从缓存中获取
        if(configuration.getCache()){
            cacheHelper.get(templateName);
        }

        if(StringUtil.isBlank(content)) {
            // 通过助手读取模板内容
            content = templateHelper.read(templateName);
        }

        if(StringUtil.isBlank(content)){
            return "";
        }

        // 加入缓存
        cacheHelper.set(templateName, content);

        // 通过助手解析html内容
        Document document = templateHelper.parse(content);

        VirtualDOMTree virtualDOM = templateHelper.createVirtualDOM(document);
//        System.out.println(JSONUtil.toJsonPrettyStr(virtualDOM.getTree()));

        RendererHelper rendererHelper = RendererHelper.getInstance();

        // 添加内置数据
        data.put("configuration", configuration);

        VariableHelper variableHelper = VariableHelper.getInstance();
        variableHelper.set(data);

        String html = rendererHelper.render(virtualDOM);

        return html;
    }
}
